/**
 * 
 */
package main.org.form.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;

import org.compiere.dsr.DSR_DataCollection;
import org.compiere.dsr.DSR_ExcelImport;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPMForm;
import org.compiere.model.MBPMFormCode;
import org.compiere.process.DSR_GenerateReport;
import org.compiere.process.ProcessInfo;
import org.compiere.util.Env;

import extend.org.compiere.utils.Util;

/**
 * @author V.Sokolov
 * 
 */
public class DownloadExcelAction extends FormBP {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2020965374760216291L;

	private InputStream fileInputStream;
	private String filename;

	/* 
	 */
	@Override
	public String execute() throws Exception {

		FormBP foBP = (FormBP) session.get(FormBP.sessionKey);
		MBPMForm form = new MBPMForm(Env.getCtx(), getBPM_Form_ID(), null);
		setFilename(form.getName());
		filename = new URI(null, filename, null).toASCIIString();
		String nameProcess = DSR_GenerateReport.class.getName();
		int AD_Process_ID = Util.getAD_Process(nameProcess.substring(
				nameProcess.lastIndexOf(".") + 1, nameProcess.length()));
		// Prepare Process
		ProcessInfo pi = new ProcessInfo("The recalculate form values",
				AD_Process_ID);
		// Prepare Process
		pi.setAD_User_ID(getAD_User_ID());
		pi.setAD_Client_ID(getAD_Client_ID());

		String path = Util.localFilePath + "pattern" + ".xls";
		MAttachmentEntry entry = Util.getAttachment(pi, Env.getCtx(), path);
		DSR_DataCollection collection;
		if (getBPM_Form_ID()==foBP.getBPM_Form_ID()&&getBPM_Project_ID()==foBP.getBPM_Project_ID()
			&&getAD_Org_ID()==foBP.getAD_Org_ID()&&getAD_Client_ID()==foBP.getAD_Client_ID())
			collection = foBP.collection;
		else 
		    collection = new DSR_DataCollection(getBPM_Form_ID(),getBPM_Project_ID(), getAD_Org_ID(),getAD_Client_ID());
		File outFile = DSR_ExcelImport.collectionImport(entry, collection);

		if (!outFile.exists())
			return NONE;

		fileInputStream = new FileInputStream(outFile);

		return SUCCESS;
	}

	public InputStream getFileInputStream() {
		return fileInputStream;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

}
